package top.swimmer.tokenizer;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import top.swimmer.tools.str.StringUtils;

import java.io.IOException;
import java.util.Date;

public class JsonTest {
    private static final ObjectMapper mapper = new ObjectMapper();

    static {
        //序列化时，跳过null属性
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //序列化时，遇到空bean（无属性）时不会失败
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        //反序列化时，遇到未知属性（在bean上找不到对应属性）时不会失败
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //反序列化时，将空数组([])当做null来处理（以便把空数组反序列化到对象属性上——对php生成的json的map属性很有用）
        mapper.configure(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT, true);
        //不通过fields来探测（仅通过标准getter探测）
        mapper.configure(MapperFeature.AUTO_DETECT_FIELDS, false);
    }

    public static void main(String[] args) {
        test();
    }

    public static void test() {
        JsonDemo demo1 = new JsonDemo();
        demo1.setS("demo1");
        demo1.setI(111);
        demo1.setJsonInterface(new JsonInterface() {
            @Override
            public Date setA() {
                return new Date(0);
            }

            @Override
            public String setB() {
                return "demo11111";
            }
        });

        JsonDemo demo2 = new JsonDemo();
        demo2.setS("demo2");
        demo2.setI(222);
        demo2.setJsonInterface(new JsonInterface() {
            @Override
            public Date setA() {
                return new Date();
            }

            @Override
            public String setB() {
                return "demo22222";
            }
        });

        String demo1Str = writeToString(demo1);
        System.out.println(demo1Str);
        JsonDemo demo1P = parse(demo1Str, JsonDemo.class);
        System.out.println(demo1Str);
    }

    /**
     * Json串转为对象
     * @param json json
     * @param type type
     * @param <T> T
     * @return T
     */
    public static <T> T parse(String json, Class<T> type) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        try {
            return mapper.readValue(json, type);
        } catch (IOException e) {
            return null;
        }
    }

    /**
     * 序列化对象转为json-string
     * @param target target
     * @return String
     */
    public static String writeToString(Object target) {
        try {
            return mapper.writeValueAsString(target);
        } catch (JsonProcessingException e) {
            return "";
        }
    }
}

